package com.agile.leetcode.node.slowfastpointer;

/**
 * 判断链表是否具有循环链表
 *
 * @Author ChenZhangKun
 * @Date 2020/12/23 11:36
 */
public class CircleNode {
    public static void main(String[] args) {

        NodeDemo nodeDemo5 = new NodeDemo(1, null);
        NodeDemo nodeDemo4 = new NodeDemo(1, nodeDemo5);
        NodeDemo nodeDemo3 = new NodeDemo(1, nodeDemo4);
        NodeDemo nodeDemo2 = new NodeDemo(1, nodeDemo3);
        NodeDemo nodeDemo1 = new NodeDemo(1, nodeDemo2);
        test(nodeDemo5, nodeDemo3);
        System.out.println(hasCycle(nodeDemo1));
    }

    public static void test(NodeDemo nodeDemo1, NodeDemo nodeDemo2) {
        nodeDemo1.next = nodeDemo2;
    }

    /**
     * 是否具有循环链表的快慢指针法
     *
     * @param nodeDemo
     * @return
     */
    public static boolean hasCycle(NodeDemo nodeDemo) {
        NodeDemo slow = nodeDemo;
        NodeDemo fast = nodeDemo;
        while (slow != null && fast != null&&fast.next!=null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                return true;
            }
        }
        return false;

    }
}

class NodeDemo {
    int value;
    NodeDemo next;

    public NodeDemo(int value, NodeDemo next) {
        this.value = value;
        this.next = next;
    }

    @Override
    public String toString() {
        return "NodeDemo{" +
                "value=" + value +
                ", next=" + next +
                '}';
    }
}

